/**
 * Created by ocean on 3/3/14.
 */
const WEBSITE_HAIVL_COM = 1;
const WEBSITE_HAIVL_TV = 2;

var playerSize = {
    1: {
        width: 400,
        height: 300
    },
    2: {
        width: 728,
        height: 410
    }
};

var iframeTemplate = '<iframe width="{{width}}" height="{{height}}" src="//www.youtube.com/embed/{{youtube_id}}?show_info=0&nologo=1&autoplay=1" frameborder="0" allowfullscreen></iframe>';

function bindEvent(els, whichSite){
    $(els).click(function(e){
        convertToPlayer(this, whichSite, e);
    });
}

function getPlayerIframe(whichSite, videoId) {
    var playerIframe = $(iframeTemplate.replace(/{{width}}|{{height}}|{{youtube_id}}/gi, function(matched){
        if (matched == '{{youtube_id}}') {
            return videoId;
        } else {
            return playerSize[whichSite][matched.replace(/{{|}}/gi, '')];
        }
    }));

    return playerIframe;
}

function convertToPlayer(el, whichSite, event){
    switch (whichSite) {
        case WEBSITE_HAIVL_COM:
            var thumb = $(el);

            if (thumb.data('quick-tube-processed')) {
                return;
            }

            var thumbImg = thumb.find('.thumbImg');

            if (thumbImg.length) {
                var youtubeThumbImgUrl = thumbImg[0].src;
                if (youtubeThumbImgUrl.indexOf('youtube.com') == -1) {
                    return;
                }

                event.preventDefault();

                var urlParts = youtubeThumbImgUrl.split('/');
                var videoId = urlParts[urlParts.length - 2];
                var playerIframe = getPlayerIframe(whichSite, videoId);
                playerIframe.appendTo(thumb.parent());
                thumb.remove();
                thumb.data('quick-tube-processed', true);
            }
            break;
        case WEBSITE_HAIVL_TV:
            event.preventDefault();
            var thumb = $(el);
            var videoId = thumb.data('youtubeid');
            if (videoId != undefined) {
                var playerIframe = getPlayerIframe(whichSite, videoId);
                playerIframe.appendTo(thumb.parent());
                thumb.remove();
            }
            break;
    }
}

function run() {
    var href = window.location.href;
    if (href.indexOf('haivl.tv') > -1) {
        bindEvent($('.videoListItem .play'), WEBSITE_HAIVL_TV);
    } else {
        bindEvent($('.photoListItem .thumbnail a'), WEBSITE_HAIVL_COM);
    }
}

document.addEventListener('DOMContentLoaded', run, false);
document.addEventListener("DOMNodeInserted", run, false);